/**
 * Copyright (C) 2010 MOBICOM. All rights reserved.
 * 
 * 
 * This software is the confidential and proprietary information of
 * Mobicom or one of its subsidiaries. You shall not disclose this
 * confidential information and shall use it only in accordance with
 * the terms of the license agreement or other applicable agreement
 * you entered into with Mobicom.
 * 
 * MOBICOM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. MOBICOM
 * SHALL NOT BE LIABLE FOR ANY LOSSES OR DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR
 * ITS DERIVATIVES.
 * 
 * Apr 10, 2011 2:25:30 PM
 * 
 * @author Nguyen Dinh Phuoc Duc(ndpduc@gmail.com)
 */
package com.lily.smsbox.screen;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.provider.Telephony.Sms.Conversations;
import com.android.provider.Telephony.Threads;
import com.lily.mysms.R;
import com.lily.smsbox.helper.ContactHelper;
import com.lily.smsbox.helper.MmsSmsHelper;
import com.lily.smsbox.model.Contact;
import com.lily.smsbox.model.Conversation;
import com.lily.smsbox.model.MessageThread;
import com.lily.smsbox.util.Utils;

/**
 * Internal Class
 * 
 * @author Nguyen Dinh Phuoc Duc (ndpduc@gmail.com)
 * 
 */
public class ConversationActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.conversations);

  }

  @Override
  protected void onResume() {
    super.onResume();
    reloadConversations();
  }

  private void reloadConversations() {
    ContentResolver cr = getContentResolver();
    Cursor c =
        cr.query(
            Threads.CONTENT_URI,
            null,
            null,
            null,
            Threads.DATE);

    List<MessageThread> conversations = new ArrayList<MessageThread>();
    while (c.moveToNext()) {
      MessageThread thread = new MessageThread();
      thread.id =
          c.getInt(c.getColumnIndex(Threads._ID));
//      thread.snippet =
//          c.getString(c.getColumnIndex(Threads.SNIPPET));
      thread.message_count =
          c.getInt(c.getColumnIndex(Threads.MESSAGE_COUNT));
      conversations.add(thread);
    }
    c.close();
    TextView textCount = (TextView) findViewById(R.id.text_count);
    textCount.setText(conversations.size()
        + ((conversations.size() > 1) ? " conversations"
            : " conversation"));
    ArrayAdapter<MessageThread> adapter =
        new ArrayAdapter<MessageThread>(
            this,
            R.layout.li_conversation,
            conversations) {
          private MmsSmsHelper _helper = new MmsSmsHelper(getContext());

          @Override
          public long getItemId(int position) {
            return position;
          }

          @Override
          public View getView(int position, View convertView,
              ViewGroup parent) {
            if (convertView == null) {
              convertView =
                  LayoutInflater.from(getContext()).inflate(
                      R.layout.li_conversation,
                      null);
            }
            MessageThread item = getItem(position);
//            MessageThread thread =
//                _helper.getThreadById(item.threadId);

            TextView textAddress =
                (TextView) convertView
                    .findViewById(R.id.text_address);

            ContactHelper cHelper = new ContactHelper(getApplicationContext());
//            Contact contact = cHelper.getContactByKey(thread.address);
            
            textAddress.setText(item.id +  " (" + item.message_count + ")");

            TextView textSnippet =
                (TextView) convertView
                    .findViewById(R.id.text_snippet);
            textSnippet.setText(item.snippet);

            TextView textWhen =
                (TextView) convertView.findViewById(R.id.text_when);
            textWhen.setText(makeTimeString(item.date));

            ImageView imageContact =
                (ImageView) convertView
                    .findViewById(R.id.image_contact);
//            Bitmap bitmap =
//                getPhoto(
//                    getContentResolver(), contact == null ? 0 : contact.id);
//            if (bitmap != null) {
//              imageContact.setImageBitmap(bitmap);
//            } else {
//              imageContact.setImageResource(R.drawable.icon);
//            }
//            if (thread.readStatus == 0) {
//              convertView.setBackgroundColor(0x8F777777);
//            } else {
//              convertView.setBackgroundColor(0x000000);
//            }
            return convertView;
          }
        };
    ListView listCons =
        (ListView) findViewById(R.id.list_conversation);
    listCons.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> adapterView,
          View convertView, int position, long id) {
        Conversation conversation =
            (Conversation) adapterView.getAdapter().getItem(position);
        Intent i =
            new Intent(
                ConversationActivity.this,
                ThreadActivity.class);
        i.putExtra("threadid", conversation.threadId);
        startActivity(i);
      }
    });
    listCons.setAdapter(adapter);
  }

  private String makeTimeString(long time) {
    Date now = new Date();
    Date date = new Date(time);

    String text =
        (now.getDate() == date.getDate()) ? Utils
            .longToDateFormatString("HH:mm", time) : Utils
            .longToDateFormatString("d MMM", time);

    return text;
  }

  private String getPerson(ContentResolver cr, long personId) {
    Contact contact =
        new ContactHelper(getApplicationContext())
            .getContactById(personId);
    return (contact != null ? contact.displayName : "");
  }

  private String getPerson(ContentResolver cr, String key) {
    Contact contact =
        new ContactHelper(getApplicationContext())
            .getContactByKey(key);
    return (contact != null ? contact.displayName : "");
  }

  public Bitmap getPhoto(ContentResolver contentResolver,
      long contactId) {
    Uri contactPhotoUri =
        ContentUris.withAppendedId(People.CONTENT_URI, contactId);

    // contactPhotoUri -->
    // content://com.android.contacts/contacts/1557

    
//    InputStream photoDataStream =
//        ContactsContract.Contacts.openContactPhotoInputStream(
//            contentResolver,
//            contactPhotoUri); // <-- always null
//    Bitmap photo = BitmapFactory.decodeStream(photoDataStream);
    Bitmap photo = People.loadContactPhoto(getApplicationContext(), contactPhotoUri, R.drawable.icon, null);
    return photo;
  }
}
